# -*- coding: utf-8 -*-
__author__ = 'Administrator'

import win32print
import urllib2,time
import builder, winGuiAuto,ConfigParser
import semiauto
from log import Logger
import winTools_operate

ExceptionDict = {"ui_flow_prdsts_error::st_dev_mech_err_ok_change_cancel_action":"Paper size mismatch!",
                 "ui_flow_prdsts_error::st_dev_mech_err_ok_showme_cancel":"Paper jam happened, please check printer",
                 "ui_flow_prdsts_error::st_dev_mech_err_icon_showme_cancel":"Please feed enough paper !",
                 "ui_flow_prdsts_error::st_dev_mech_err_ok_showme_action":"Please close the Door !",
                 "ui_flow_prdsts_error::st_dev_ink_err_ok_showme_action":"Shorting of ink, Please change Cartridge !",
                 "ui_flow_prdsts_error::st_dev_mech_tray_out_of_paper":"Load paper in tray, Please check Printer !",
                 "ui_flow_prdsts_error::st_dev_jam_locations":"Paper jam happened, Please check Printer !",
                 "ui_flow_prdsts_error::st_dev_mech_err_ok_action":"Maybe paper is not loaded or shorting of paper, please check Printer!"}
PrintingDic = {"devicejobs::st_job_progress_print":"print",
              "ui_fl_setup_status::st_print_report_status":"Global_Status_PrintingReports"}
OutOfPaper = {"ui_flow_prdsts_error::st_dev_mech_tray_out_of_paper":"LEDM"}

NormalDict = {"flow_home::state_home":"Home",
              "devicejobs::st_job_progress_print":"print",
              "ui_fl_setup_status::st_print_report_status":"Global_Status_PrintingReports"}

builder1 = builder.TestBuilder.getBuilder()
logger = Logger.getLogger()
def setDefaultPrint(printerName):
    '''
    printName:print name for using priner
    '''
    if win32print.GetDefaultPrinter() == printerName:
        pass
    else:
        win32print.SetDefaultPrinter(printerName)

def getScreenID():
    response = urllib2.urlopen("http://"+builder1.getConfig(property = 'printer_ip')+"/TestService/UI/ScreenInfo")
    htmlContent = response.read()
    startId = htmlContent.find("<ScreenId>")
    endId = htmlContent.find("</ScreenId>")
    ScreenId = ""
    for i in range(startId + 10,endId):
        ScreenId = ScreenId + htmlContent[i]
    return ScreenId

def isCoreDump(ip):
    try:
        urllib2.urlopen("http://"+ip+"/TestService/UI/ScreenInfo", timeout=120)
    except Exception , e:
        return True
    return False

def isExceptionScreen():
    if ExceptionDict.has_key(getScreenID()):
        return True
    else:
        return False

def isOutOfPaper():
    if PrintingDic.has_key(getScreenID()):
        return True
    return False

def isPaperJam():
    return False

def isDoorOpened():
    return False

def isPrinting():
    logger.debug('screen id:'+getScreenID())
    if PrintingDic.has_key(getScreenID()):
        return True
    return False

def isPrinting_type2():
    is_dialog_display =winTools_operate.checkDialogDisplayed(wantedText='WinWrap Basic',wantedControlClass='Button', wantedControlText='Clear')
    if PrintingDic.has_key(getScreenID()) and not is_dialog_display:
        return True
    return False

def exceptionHandlerBeforePrinting():
    #Check if exception happened,, if true, wait until added
    logger.debug("Check whether exception happened before print...")
    if not isExceptionScreen():
        logger.debug("No exception before print")
    else:
        logger.debug("Exception happened before print:" + getScreenID())
        semiauto.showinfo(ExceptionDict.get(getScreenID()))


def exceptionHandlerPrinting(timeout=120):
    #Check if exception happened,, if true, wait until added
    logger.debug("Check whether exception happened while printing...")
    if not isExceptionScreen():
        logger.debug("No exception while printing")
    else:
        logger.debug("Exception happened while printing:" + getScreenID())
        semiauto.showinfo(ExceptionDict.get(getScreenID()))
        time.sleep(2)
        printTime = 0
        while isPrinting():
            logger.debug("After handling exception, printer is printing...")
            time.sleep(2)
            printTime = printTime + 2
            if printTime > timeout or printTime == timeout :
                logger.debug("After handling exception, print time out...")
                return False
        return True
    return True

def exceptionHandlerPrinting_type2(timeout=120):
    #Check if exception happened,, if true, wait until added
    logger.debug("Check whether exception happened while printing...")
    if not isExceptionScreen():
        logger.debug("No exception while printing")
    else:
        logger.debug("Exception happened while printing:" + getScreenID())
        semiauto.showinfo(ExceptionDict.get(getScreenID()))
        time.sleep(2)
        printTime = 0
        while isPrinting_type2():
            logger.debug("After handling exception, printer is printing...")
            time.sleep(2)
            printTime = printTime + 2
            if printTime > timeout or printTime == timeout :
                logger.debug("After handling exception, print time out...")
                return False
        return True
    return True

def printing_status_type2(timeout=120):
    logger.debug('Check print status...')
    exceptionHandlerBeforePrinting()
    time.sleep(1.5)
    printTime = 0
    while isPrinting_type2():
        logger.debug('Device is printing...')
        time.sleep(2)
        printTime = printTime+2
        if printTime > timeout or printTime == timeout :
            logger.debug('Print timeout...')
            return False
    return exceptionHandlerPrinting_type2(timeout)

def printing_status(timeout=120):
    logger.debug('Check print status...')
    exceptionHandlerBeforePrinting()
    time.sleep(1.5)
    printTime = 0
    while isPrinting():
        logger.debug('Device is printing...')
        time.sleep(2)
        printTime = printTime+2
        if printTime > timeout or printTime == timeout :
            logger.debug('Print timeout...')
            return False
    return exceptionHandlerPrinting(timeout)
#unittest
if __name__=='__main__':
    config = ConfigParser.ConfigParser()
    config.readfp(open("../testcases_config.ini"))
    ip = config.get("config","printer_ip")
    isCoreDump(ip)